package cn.tedu.mvc.dao.Impl;

import cn.tedu.mvc.dao.UserDao;
import cn.tedu.mvc.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public int addUser(User user) {
        String sql = "insert into user (username, password) values (?,?)";

        try(Connection conn = dataSource.getConnection()) {
            PreparedStatement ps =  conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            int i = ps.executeUpdate();
            ResultSet rs = ps.getGeneratedKeys();
            while (rs.next()){
                user.setId(rs.getInt(1));
            }
            return i;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }


    }

    @Override
    public User getUserByName(String username) {
        User user = null;
        String sql = "select * from user where username=?";
        try (Connection conn = dataSource.getConnection()){
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("username");
                String pwd = rs.getString("password");
                user = new User(id,name,pwd);
            }
            return user;
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public User getUserById(Integer userid) {
        User user = null;
        String sql = "select * from user where id=?";
        try (Connection conn = dataSource.getConnection()){
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setInt(1,userid);
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("username");
                String pwd = rs.getString("password");
                user = new User(id,name,pwd);
            }
            return user;
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
